package tss.datastore;

import org.joda.time.DateTime;

import tss.datastore.meta.AttributeDefinition;
import tss.datastore.meta.EntityDefinition;
import tss.datastore.meta.MetaPersister;

public class DataStore {
    
    private MetaPersister metaPersister;
    private DataPersister dataPersister;
    
    public DataStore(MetaPersister metaPersister) {
        this.metaPersister = metaPersister;
    }
    
    public void createEntity(long entityId) {
        EntityDefinition existing = metaPersister.loadEntity(entityId);
        if (existing != null) {
            throw new RuntimeException("Entity " + entityId + " is already existed.");
        } else {            
            metaPersister.writeEntity(new EntityDefinition(entityId));
        }        
    }

    public void addAttribute(long entityId, String attributeName, ValueType attributeType) {
        EntityDefinition entity = metaPersister.loadEntity(entityId);
        if (entity == null) {
            throw new RuntimeException("Entity " + entityId + " does not exist.");
        }
        AttributeDefinition attribute = new AttributeDefinition(attributeName, attributeType);
        boolean added = entity.AddAttribute(attribute);
        if (!added) {
            throw new RuntimeException("Attribute " + attributeName + " is already existed.");
        }
    }

    public <T> void addDataPoint(long entityId, String attributeName, DateTime dateTime, T value) {
        

    }

    public <T> T queryValue(long entityId, String attributeName, DateTime dateTime) {
        // TODO Auto-generated method stub
        return null;
    }

    public boolean entityExist(long entityId) {
        return metaPersister.loadEntity(entityId) != null;
    }

    public boolean attributeExist(long entityId, String attributeName) {
        EntityDefinition entity = metaPersister.loadEntity(entityId);
        if (entity != null) {
            return entity.getAttribute(attributeName) != null;
        } else {
            return false;
        }
    }

}
